package com.deepwiki.controller;

import com.deepwiki.domain.entity.Warehouse;
import com.deepwiki.domain.enums.WarehouseStatus;
import com.deepwiki.service.WarehouseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 仓库管理API控制器
 */
@RestController
@RequestMapping("/api/warehouse")
@CrossOrigin(origins = "*")
public class WarehouseController {

    private static final Logger logger = LoggerFactory.getLogger(WarehouseController.class);

    private final WarehouseService warehouseService;

    @Autowired
    public WarehouseController(WarehouseService warehouseService) {
        this.warehouseService = warehouseService;
    }

    /**
     * 创建新的仓库并开始wiki生成
     *
     * @param request 创建请求
     * @return 操作结果
     */
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createWarehouse(@RequestBody CreateWarehouseRequest request) {
        try {
            logger.info("创建仓库: {}", request.getAddress());
            
            // 验证请求参数
            if (request.getAddress() == null || request.getAddress().trim().isEmpty()) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "仓库地址不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 创建仓库
            Warehouse warehouse = warehouseService.createWarehouse(request);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "仓库创建成功，正在生成Wiki");
            response.put("warehouseId", warehouse.getId());
            response.put("status", warehouse.getStatus());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("创建仓库失败: {}", request.getAddress(), e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "创建仓库失败: " + e.getMessage());
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 获取仓库状态
     *
     * @param warehouseId 仓库ID
     * @return 仓库状态
     */
    @GetMapping("/{warehouseId}/status")
    public ResponseEntity<Map<String, Object>> getWarehouseStatus(@PathVariable String warehouseId) {
        try {
            Warehouse warehouse = warehouseService.getWarehouse(warehouseId);
            if (warehouse == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "仓库不存在");
                return ResponseEntity.notFound().build();
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("warehouseId", warehouse.getId());
            response.put("status", warehouse.getStatus());
            response.put("name", warehouse.getName());
            response.put("address", warehouse.getAddress());
            response.put("organizationName", warehouse.getOrganizationName());
            response.put("description", warehouse.getDescription());
            response.put("error", warehouse.getError());
            response.put("createdAt", warehouse.getCreatedAt());
            response.put("updatedAt", warehouse.getUpdatedAt());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取仓库状态失败: {}", warehouseId, e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取仓库状态失败: " + e.getMessage());
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 获取所有仓库列表
     *
     * @return 仓库列表
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getWarehouseList() {
        try {
            List<Warehouse> warehouses = warehouseService.getAllWarehouses();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", warehouses);
            response.put("total", warehouses.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取仓库列表失败", e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取仓库列表失败: " + e.getMessage());
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 重新生成仓库wiki
     *
     * @param warehouseId 仓库ID
     * @return 操作结果
     */
    @PostMapping("/{warehouseId}/regenerate")
    public ResponseEntity<Map<String, Object>> regenerateWarehouse(@PathVariable String warehouseId) {
        try {
            logger.info("重新生成仓库wiki: {}", warehouseId);
            
            warehouseService.regenerateWarehouse(warehouseId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "重新生成任务已启动");
            response.put("warehouseId", warehouseId);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("重新生成仓库wiki失败: {}", warehouseId, e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "重新生成仓库wiki失败: " + e.getMessage());
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 删除仓库
     *
     * @param warehouseId 仓库ID
     * @return 操作结果
     */
    @DeleteMapping("/{warehouseId}")
    public ResponseEntity<Map<String, Object>> deleteWarehouse(@PathVariable String warehouseId) {
        try {
            logger.info("删除仓库: {}", warehouseId);
            
            warehouseService.deleteWarehouse(warehouseId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "仓库删除成功");
            response.put("warehouseId", warehouseId);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("删除仓库失败: {}", warehouseId, e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "删除仓库失败: " + e.getMessage());
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 创建仓库请求DTO
     */
    public static class CreateWarehouseRequest {
        private String address;
        private String name;
        private String description;
        private String type = "git";
        private String branch = "main";
        private String username;
        private String password;
        private String email;

        // Getters and Setters
        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getBranch() {
            return branch;
        }

        public void setBranch(String branch) {
            this.branch = branch;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }
    }
} 